package com.koo.common.utils;

import com.alibaba.csp.sentinel.util.StringUtil;
import com.koo.common.exception.RRException;

import java.security.MessageDigest;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;

public class SignUtil {
    public SignUtil() {
    }

    public static String generateSignature(Map data, String apiSecret) {
        return generateSignature(data, apiSecret, "apiSecret");
    }

    public static String generateSignature(Map data, String apiSecret, String keyName) {
        Set<String> keySet = data.keySet();
        String[] keyArray = (String[])keySet.toArray(new String[keySet.size()]);
        Arrays.sort(keyArray);
        StringBuilder sb = new StringBuilder();
        int len = keyArray.length;

        for(int i = 0; i < len; ++i) {
            String k = keyArray[i];
            if (!k.equals("sign")) {
                Object value = data.get(k);
                if (value != null && value instanceof String && value.toString().trim().length() > 0) {
                    sb.append(k).append("=").append(value.toString().trim()).append("&");
                }
            }
        }
        sb.append((StringUtil.isEmpty(keyName) ? "apiSecret" : keyName) + "=").append(apiSecret);
        return MD5(sb.toString()).toUpperCase();
    }

    public static String MD5(String data) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] array = md.digest(data.getBytes("UTF-8"));
            StringBuilder sb = new StringBuilder();
            int len = array.length;

            for(int i = 0; i < len; ++i) {
                byte item = array[i];
                sb.append(Integer.toHexString(item & 255 | 256).substring(1, 3));
            }
            return sb.toString().toUpperCase();
        } catch (Exception var8) {
            throw new RRException("参数签名错误");
        }
    }
}
